package com.tensquare.chat.service;
/*
 *ClassName:MessageService
 *Description:
 *@author:可爱的大鸭子
 */

import com.tensquare.chat.ChatApplication;
import com.tensquare.chat.client.FriendClient;
import com.tensquare.chat.dao.MessageDao;
import com.tensquare.chat.pojo.SocketMessage;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import util.IdWorker;

import java.util.*;

@Service
public class MessageService {
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private FriendClient friendClient;
    @Autowired
    private MongoTemplate mongoTemplate;

    //存储聊天消息
    public void add(SocketMessage message){
        message.set_id(idWorker.nextId()+"");
        message.setPublishtime(new Date());
        //判断对方是否登录
        String sessionId= ChatApplication.sessionMap.get(message.getTo());
        if(sessionId==null||sessionId.equals("")){
            //对方没有上线
            message.setReaded("0");         //设置对方消息未读
        }
        else {
            //对方在线
            message.setReaded("1");         //消息已读
        }
        //to从前端是已知的，封装在message中,from也是已知的
        messageDao.save(message);
    }

    //查询聊天记录
    public List<SocketMessage> getChatList(String from, String to) {
        List list1= messageDao.findAllByFromAndToOrderByPublishtimeDesc(from,to);
        List list2= messageDao.findAllByFromAndToOrderByPublishtimeDesc(to,from);
        list1.addAll(list2);
        Collections.sort(list1, new Comparator<SocketMessage>() {
            @Override
            public int compare(SocketMessage o1, SocketMessage o2) {
                return o1.getPublishtime().toString().compareTo(o2.getPublishtime().toString());
            }
        });
        return list1;
    }

    //查询我的未读消息总数
    public Integer getMyMessages(String userId) {
        return messageDao.countAllByToAndReaded(userId,"0");
    }

    //查询我的的最新的未读的消息详情，一个人的多条消息只返回最新的一个，并且返回未读的消息数量
    public List<SocketMessage> findMessages(String to){
        Result result=friendClient.findMyFriends(to);
        List<String> list=(List)result.getData();
        List<SocketMessage> res=new ArrayList<>();
        for(String from:list){
            SocketMessage message=messageDao.findTopByFromAndToAndReadedOrderByPublishtimeDesc(from,to,"0");
            if(message!=null){
                //封装填入count
                Integer count=messageDao.countAllByFromAndToAndReaded(from,to,"0");
                message.setCount(count);
                res.add(message);
            }
        }
        return res;
    }

    //设置已读，返回数量
    public void setReaded(String from, String to) {
        Query query = new Query();
        query.addCriteria(Criteria.where("from").is(from));
        query.addCriteria(Criteria.where("to").is(to));
        query.addCriteria(Criteria.where("readed").is("0"));
        Update update = new Update();
        update.set("readed","1");
        mongoTemplate.updateMulti(query,update,SocketMessage.class);
    }
}
